package backend.project.gym_management.service.impl;

import backend.project.gym_management.pojo.dto.*;
import backend.project.gym_management.mapper.AdminMapper;
import backend.project.gym_management.service.AdminService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.*;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminServiceImpl<E> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    // 允许查询的表名集合
    private static final Set<String> ALLOWED_TABLES = Set.of(
            "coach_introduction", "course", "course_introduction",
            "employee", "enrollment", "equipment", "health_data",
            "order", "payment_record", "repair_status", "user","pay_order"
    );


    /**
     * 检查表名
     * 用于检查表名是否存在，如果不存在则抛出异常
     * @param tableName
     */
    public void checkTableName(String tableName) {
        if (!ALLOWED_TABLES.contains(tableName)) {
            throw new IllegalArgumentException("未知表名: " + tableName);
        }
    }

    /**
     * 查询数据表
     * 根据AdminQuery参数中的tableName来进行表名的动态查询，并返回查询结果
     * @param query
     * @return List集合
     */
    @SuppressWarnings("unchecked")
    public List<E> query(AdminQuery query) {
        String tableName = query.getTableName();
        checkTableName(tableName);

        // 根据表名分发到不同的 Mapper 方法
        return (List<E>) switch (tableName) {
            case "coach_introduction" -> adminMapper.queryCoachIntroduction(query);
            case "course" -> adminMapper.queryCourse(query);
            case "course_introduction" -> adminMapper.queryCourseIntroduction(query);
            case "employee" -> adminMapper.queryEmployee(query);
            case "enrollment" -> adminMapper.queryEnrollment(query);
            case "equipment" -> adminMapper.queryEquipment(query);
            case "health_data" -> adminMapper.queryHealthData(query);
            case "order" -> adminMapper.queryOrder(query);
            case "payment_record" -> adminMapper.queryPaymentRecord(query);
            case "repair_status" -> adminMapper.queryRepairStatus(query);
            case "user" -> adminMapper.queryUser(query);
            case "pay_order" -> adminMapper.queryPayOrder(query);
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };


    }

    /**
     * 删除数据表功能
     * 根据所给的表名、id、名称进行动态删除
     * @param adminDelete
     * @return boolean
     */
    public boolean delete(AdminDeleteParam adminDelete) {
        log.debug("开始处理删除表数据请求，参数：" + adminDelete);
        String tableName = adminDelete.getTableName();
        checkTableName(tableName);
        log.debug("删除表名：" + tableName);

        // 根据表名分发到不同的删除方法
        int result = switch (tableName) {
            case "coach_introduction" -> adminMapper.deleteCoachIntroduction(adminDelete.getTableName(), adminDelete.getId());
            case "course" -> adminMapper.deleteCourse(adminDelete);
            case "course_introduction" -> adminMapper.deleteCourseIntroduction(adminDelete.getTableName(), adminDelete.getId());
            case "employee" -> adminMapper.deleteEmployee(adminDelete);
            case "enrollment" -> adminMapper.deleteEnrollment(adminDelete.getTableName(), adminDelete.getId(),adminDelete.getUid());
            case "equipment" -> adminMapper.deleteEquipment(adminDelete);
            case "health_data" -> adminMapper.deleteHealthData(adminDelete.getTableName(), adminDelete.getId());
            case "order" -> adminMapper.deleteOrder(adminDelete.getTableName(), adminDelete.getId());
            case "payment_record" -> adminMapper.deletePaymentRecord(adminDelete.getTableName(), adminDelete.getId());
            case "repair_status" -> adminMapper.deleteRepairStatus(adminDelete.getTableName(), adminDelete.getId());
            case "user" -> adminMapper.deleteUser(adminDelete);
            case "pay_order" -> adminMapper.deletePayOrder(adminDelete.getId().longValue());
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };

        // 返回结果用于判断是否删除
        return result > 0;
    }

    /**
     * 新增数据表功能
     * 根据传入的json格式转换为对应的表字段进行添加
     * @param adminAdd
     * @return boolean
     */
    public boolean add(AdminAdd adminAdd) {
        String tableName = adminAdd.getTableName();
        checkTableName(tableName);
        //
        ObjectMapper objectMapper = new ObjectMapper();
        log.debug("新增表名：" + tableName);

        int result = switch (tableName) {
            case "user" -> {
                UserAddDTO dto = objectMapper.convertValue(adminAdd.getData(), UserAddDTO.class);
                yield adminMapper.insertUser(dto);
            }
            case "employee" -> {
                EmployeeAddDTO dto = objectMapper.convertValue(adminAdd.getData(), EmployeeAddDTO.class);
                yield adminMapper.insertEmployee(dto);
            }
            case "health_data" -> {
                HealthDataAddDTO dto = objectMapper.convertValue(adminAdd.getData(), HealthDataAddDTO.class);
                yield adminMapper.insertHealthData(dto);
            }
            case "equipment" -> {
                EquipmentAddDTO dto = objectMapper.convertValue(adminAdd.getData(), EquipmentAddDTO.class);
                yield adminMapper.insertEquipment(dto);
            }
            case "course" -> {
                CourseAddDTO dto = objectMapper.convertValue(adminAdd.getData(), CourseAddDTO.class);
                yield adminMapper.insertCourse(dto);
            }
            case "enrollment" -> {
                EnrollmentAddDTO dto = objectMapper.convertValue(adminAdd.getData(), EnrollmentAddDTO.class);
                yield adminMapper.insertEnrollment(dto);
            }
            case "repair_status" -> {
                RepairStatusAddDTO dto = objectMapper.convertValue(adminAdd.getData(),RepairStatusAddDTO.class);
                yield adminMapper.insertRepairStatus(dto);
            }
            case "course_introduction" -> {
                CourseIntroductionAddDTO dto = objectMapper.convertValue(adminAdd.getData(),CourseIntroductionAddDTO.class);
                yield adminMapper.insertCourseIntroduction(dto);
            }
            case "coach_introduction" -> {
                CoachIntroductionAddDTO dto = objectMapper.convertValue(adminAdd.getData(),CoachIntroductionAddDTO.class);
                yield adminMapper.insertCoachIntroduction(dto);
            }
            case "order" -> {
                OrderAddDTO dto = objectMapper.convertValue(adminAdd.getData(),OrderAddDTO.class);
                yield adminMapper.insertOrder(dto);
            }
            case "payment_record" -> {
                PaymentRecordAddDTO dto = objectMapper.convertValue(adminAdd.getData(),PaymentRecordAddDTO.class);
                yield adminMapper.insertPaymentRecord(dto);
            }
            case "pay_order" -> {
                PayOrderAddDTO dto = objectMapper.convertValue(adminAdd.getData(),PayOrderAddDTO.class);
                yield adminMapper.insertPayOrder(dto);
            }
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };

        return result > 0;
    }


    /**
     * 修改数据表功能
     * 根据传入的json格式转换为对应的表字段进行修改
     * @param adminUpdate
     * @return boolean
     *
     */
    public boolean update(AdminUpdate adminUpdate) {
        String tableName = adminUpdate.getTableName();
        checkTableName(tableName);
        ObjectMapper objectMapper = new ObjectMapper();
        log.debug("修改表名：" + tableName);


        int result = switch (tableName) {
            case "user" -> {
                UserUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), UserUpdateDTO.class);
                yield adminMapper.updateUser(dto);
            }
            case "employee" -> {
                EmployeeUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), EmployeeUpdateDTO.class);
                yield adminMapper.updateEmployee(dto);
            }
            case "health_data" -> {
                HealthDataUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), HealthDataUpdateDTO.class);
                yield adminMapper.updateHealthData(dto);
            }
            case "equipment" -> {
                EquipmentUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), EquipmentUpdateDTO.class);
                dto.setUpdate_time(new Date());
                yield adminMapper.updateEquipment(dto);
            }
            case "course" -> {
                CourseUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), CourseUpdateDTO.class);
                yield adminMapper.updateCourse(dto);
            }
            case "enrollment" -> {
                EnrollmentUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), EnrollmentUpdateDTO.class);
                yield adminMapper.updateEnrollment(dto);
            }
            case "repair_status" -> {
                RepairStatusUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(), RepairStatusUpdateDTO.class);
                dto.setUpdate_time(new Date());
                yield adminMapper.updateRepairStatus(dto);
}

            case "course_introduction" -> {
                CourseIntroductionUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(),CourseIntroductionUpdateDTO.class);
                yield adminMapper.updateCourseIntroduction(dto);
            }
            case "coach_introduction" -> {
                CoachIntroductionUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(),CoachIntroductionUpdateDTO.class);
                yield adminMapper.updateCoachIntroduction(dto);
            }
            case "order" -> {
                OrderUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(),OrderUpdateDTO.class);
                yield adminMapper.updateOrder(dto);
            }
            case "payment_record" -> {
                PaymentRecordUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(),PaymentRecordUpdateDTO.class);
                yield adminMapper.updatePaymentRecord(dto);
            }
            case "pay_order" -> {
                PayOrderUpdateDTO dto = objectMapper.convertValue(adminUpdate.getData(),PayOrderUpdateDTO.class);
                yield adminMapper.updatePayOrder(dto);
            }
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };


        return result > 0;
    }

    /**
     * 分页查询通用方法
     * @param query 包含 tableName 和查询条件
     * @param pageNum 当前页码
     * @param pageSize 每页数量
     * @return PageInfo 分页结果
     */
    @Override
    public PageInfo<E> selectPage(AdminQuery query, int pageNum, int pageSize) {
        String tableName = query.getTableName();
        checkTableName(tableName);
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询（注意：必须紧随 startPage）
        List<E> result = (List<E>) switch (tableName) {
            case "coach_introduction" -> adminMapper.queryCoachIntroduction(query);
            case "course" -> adminMapper.queryCourse(query);
            case "course_introduction" -> adminMapper.queryCourseIntroduction(query);
            case "employee" -> adminMapper.queryEmployee(query);
            case "enrollment" -> adminMapper.queryEnrollment(query);
            case "equipment" -> adminMapper.queryEquipment(query);
            case "health_data" -> adminMapper.queryHealthData(query);
            case "order" -> adminMapper.queryOrder(query);
            case "payment_record" -> adminMapper.queryPaymentRecord(query);
            case "repair_status" -> adminMapper.queryRepairStatus(query);
            case "user" -> adminMapper.queryUser(query);
            case "pay_order" -> adminMapper.queryPayOrder(query);
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };
        // 返回分页对象
        return new PageInfo<>(result);
    }

     @Override
    public boolean checkCidExist(Integer cid) {
        if (cid == null) return false;
        Integer count = adminMapper.checkCidExist(cid);
        return count != null && count > 0;
    }
    @Override
    public boolean checkIntroductionExist(Integer cid) {
        if (cid == null) return false;
        Integer count = adminMapper.checkIntroductionExist(cid);
        return count != null && count > 0;
    }
    @Override
    public boolean batchDelete(AdminBatchDeleteParam adminBatchDelete) {
        String tableName = adminBatchDelete.getTableName();
        checkTableName(tableName);
        int result = switch (tableName) {
            case "user" -> adminMapper.batchDeleteUser(tableName, adminBatchDelete.getIds());
            case "course" -> adminMapper.batchDeleteCourse(tableName, adminBatchDelete.getIds());
            case "employee" -> adminMapper.batchDeleteEmployee(tableName, adminBatchDelete.getIds());
            case "course_introduction" -> adminMapper.batchDeleteCourseIntroduction(tableName, adminBatchDelete.getIds());
            case "repair_status" -> adminMapper.batchDeleteRepairStatus(tableName, adminBatchDelete.getIds());
            case "equipment" -> adminMapper.batchDeleteEquipment(tableName, adminBatchDelete.getIds());
            case "coach_introduction" -> adminMapper.batchDeleteCoachIntroduction(tableName, adminBatchDelete.getIds());
            case "enrollment" -> adminMapper.batchDeleteEnrollment(adminBatchDelete.getPairs());

            case "pay_order" -> adminMapper.batchDeletePayOrder(
                    adminBatchDelete.getIds().stream()
                            .map(Integer::longValue)
                            .collect(Collectors.toList())
            );
            default -> throw new IllegalArgumentException("未知表名: " + tableName);
        };
        return result > 0;
    }
@Override
public boolean checkCoachExist(Integer eid) {
  if (eid == null) return false;
  Integer count = adminMapper.checkCoachExist(eid);
  return count != null && count > 0;
}

@Override
public boolean checkCoachIntroductionExist(Integer eid) {
  if (eid == null) return false;
  Integer count = adminMapper.checkCoachIntroductionExist(eid);
  return count != null && count > 0;
}

@Override
public boolean checkEquipmentExist(Integer seid) {
    if (seid == null) return false;
    Integer count = adminMapper.checkEquipmentExist(seid);
    return count != null && count > 0;
}

@Override
public boolean checkRepairStatusExist(Integer seid) {
    Integer count = adminMapper.checkRepairStatusExist(seid);
    return count != null && count > 0;
}
@Override
public boolean checkUidExist(Integer uid) {
    Integer count = adminMapper.checkUidExist(uid);
    return count != null && count > 0;
}


}
